昨天已經學會了如何使用變數來儲存資料,但程式真正的力量在於它能夠「根據條件做判斷」與「重複執行」。今天,我們要來認識 C# 的流程控制語法,包括 if 條件判斷,以及 for、while 等迴圈。
首先是 if 判斷式,這跟 python 的概念是一樣的,就從下面的例子來看吧!
int a = 5;
int b = 6;
if (a + b > 10)
Console.WriteLine("The answer is greater than 10.");
Output->The answer is greater than 10.
此為最簡單的一個if判斷練習,若符合條件就執行判斷式下方內容。
int a = 5;
int b = 3;
if (a + b > 10)
Console.WriteLine("The answer is greater than 10");
else
Console.WriteLine("The answer is not greater than 10");
Output->The answer is not greater than 10.
加上else判斷式,也就是除了if條件內的狀況,都執行else內的內容。
switch 判斷式,如果條件分支很多,用 switch 會更清晰,也就是今天假設一個變數(grade)來存值, switch 會用這個變數的值,執行不同的程式區塊,這個值會依序與 case 條件比對,若符合就執行對應程式。default 就像 else,當所有 case 都不符合時執行。
char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("優秀");
break;
case 'B':
Console.WriteLine("良好");
break;
case 'C':
Console.WriteLine("及格");
break;
default:
Console.WriteLine("需要加油");
break;
}
Output->良好
for 迴圈通常用在需要重複執行固定次數的情境,可以看下方案例。
for (int counter = 0; counter < 10; counter++)
{
Console.WriteLine($"Hello World! The counter is {counter}");
}
Output->
Hello World! The counter is 0
Hello World! The counter is 1
Hello World! The counter is 2
Hello World! The counter is 3
Hello World! The counter is 4
Hello World! The counter is 5
Hello World! The counter is 6
Hello World! The counter is 7
Hello World! The counter is 8
Hello World! The counter is 9
也可以用字母(文字)來跑for迴圈:
for (char column = 'a'; column < 'k'; column++)
{
Console.WriteLine($"The column is {column}");
}
Output->
The column is a
The column is b
The column is c
The column is d
The column is e
The column is f
The column is g
The column is h
The column is i
The column is j
此外在for迴圈內也可以再放入一個for迴圈,可以看到會先進到第一層迴圈後執行第二層迴圈,第二層迴圈執行完畢後才回再跳出到第一層迴圈,重複執行到最外層迴圈結束:
for (int row = 1; row < 11; row++)
{
for (char column = 'a'; column < 'k'; column++)
{
Console.WriteLine($"The cell is ({row}, {column})");
}
}
Output->
The cell is (1, a)
The cell is (1, b)
The cell is (1, c)
The cell is (1, d)
The cell is (1, e)
The cell is (1, f)
The cell is (1, g)
The cell is (1, h)
The cell is (1, i)
The cell is (1, j)
The cell is (2, a)
.
.
.
The cell is (10, j)
while 迴圈則會在條件成立時持續執行:
int counter = 0;
while (counter < 10)
{
Console.WriteLine($"Hello World! The counter is {counter}");
counter++;
}
Output->
Hello World! The counter is 0
Hello World! The counter is 1
Hello World! The counter is 2
Hello World! The counter is 3
Hello World! The counter is 4
Hello World! The counter is 5
Hello World! The counter is 6
Hello World! The counter is 7
Hello World! The counter is 8
Hello World! The counter is 9
可以看到下面的程式碼,其實他的執行結果會跟上面的一樣,但差異在於:
int counter = 0;
do
{
Console.WriteLine($"Hello World! The counter is {counter}");
counter++;
} while (counter < 10);
foreach 常用來處理集合或陣列的資料:
string[] fruits = { "蘋果", "香蕉", "葡萄" ,"櫻桃"};
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
結果:
這些語法能根據某個運算式的結果,從多種可能的路徑中選擇要執行的程式碼。
DisplayWeatherReport(15.0); // Output: Cold.
DisplayWeatherReport(24.0); // Output: Perfect!
void DisplayWeatherReport(double tempInCelsius)
{
if (tempInCelsius < 20.0)
{
Console.WriteLine("Cold.");
}
else
{
Console.WriteLine("Perfect!");
}
}
如果氣溫小於 20 度,顯示「Cold.」,否則顯示「Perfect!」。
2. 狀況二只有 if,沒有 else:條件成立才執行,否則直接跳過:
DisplayMeasurement(45); // 輸出: The measurement value is 45
DisplayMeasurement(-3); // 輸出: Warning: not acceptable value! The measurement value is -3
void DisplayMeasurement(double value)
{
if (value < 0 || value > 100)
{
Console.Write("Warning: not acceptable value! ");
}
Console.WriteLine($"The measurement value is {value}");
}
如果數值小於 0 或大於 100,就會先輸出警告文字,然後再顯示實際的數值。
3. 巢狀 if(nested if),可以一層一層判斷多種情況:
DisplayCharacter('f'); // 輸出: A lowercase letter: f
DisplayCharacter('R'); // 輸出: An uppercase letter: R
DisplayCharacter('8'); // 輸出: A digit: 8
DisplayCharacter(','); // 輸出: Not alphanumeric character: ,
void DisplayCharacter(char ch)
{
if (char.IsUpper(ch))
{
Console.WriteLine($"An uppercase letter: {ch}");
}
else if (char.IsLower(ch))
{
Console.WriteLine($"A lowercase letter: {ch}");
}
else if (char.IsDigit(ch))
{
Console.WriteLine($"A digit: {ch}");
}
else
{
Console.WriteLine($"Not alphanumeric character: {ch}");
}
}
如果是大寫字母 → 輸出「大寫字母」、如果是小寫字母 → 輸出「小寫字母」、如果是數字 → 輸出「數字」、其他符號 → 輸出「不是字母或數字」。
4. switch 用來依照「模式比對」來選擇要執行的程式碼:
DisplayMeasurement(-4); // 輸出: Measured value is -4; too low.
DisplayMeasurement(5); // 輸出: Measured value is 5.
DisplayMeasurement(30); // 輸出: Measured value is 30; too high.
DisplayMeasurement(double.NaN); // 輸出: Failed measurement.
void DisplayMeasurement(double measurement)
{
switch (measurement)
{
case < 0.0:
Console.WriteLine($"Measured value is {measurement}; too low.");
break;
case > 15.0:
Console.WriteLine($"Measured value is {measurement}; too high.");
break;
case double.NaN:
Console.WriteLine("Failed measurement.");
break;
default:
Console.WriteLine($"Measured value is {measurement}.");
break;
}
}
小於 0 → 顯示「太低」、大於 15 → 顯示「太高」、是 NaN(不是數字) → 顯示「測量失敗」、其他數值 → 顯示「一般數值」。
5. 多個 case 條件在 switch 陳述式中,可以在同一個區塊指定多個 case 模式:
void DisplayMeasurement(int measurement)
{
switch (measurement)
{
case < 0:
case > 100:
Console.WriteLine($"Measured value is {measurement}; out of an acceptable range.");
break;
default:
Console.WriteLine($"Measured value is {measurement}.");
break;
}
}
當 measurement < 0 或 > 100 時,會執行同一個區塊,default 則處理其他情況。
6. Case guards-有時候單純的 case 模式不足以描述條件,這時可以在 when 後加上一個布林表達式,作為額外條件:
void DisplayMeasurements(int a, int b)
{
switch ((a, b))
{
case (> 0, > 0) when a == b:
Console.WriteLine($"Both measurements are valid and equal to {a}.");
break;
case (> 0, > 0):
Console.WriteLine($"First measurement is {a}, second measurement is {b}.");
break;
default:
Console.WriteLine("One or both measurements are not valid.");
break;
}
}
結果:
First measurement is 3, second measurement is 4.
Both measurements are valid and equal to 5.